/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.hvtt.web.controller;

import com.hvtt.web.connection.Command;
import com.hvtt.web.connection.WEBConnection;
import com.hvtt.web.connection.WEBParamCollection;
import com.hvtt.web.models.RPT_TongCashoutModel;
import com.hvtt.web.utilities.Utilities;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import org.primefaces.model.DefaultTreeNode;
import org.primefaces.model.StreamedContent;
import org.primefaces.model.TreeNode;
import org.primefaces.model.chart.CartesianChartModel;
import org.primefaces.model.chart.LineChartSeries;
import org.primefaces.model.chart.PieChartModel;

/**
 *
 * @author Administrator
 */
@ManagedBean
@SessionScoped
public class RPT_TongCashoutController   implements Serializable {
     private WEBConnection DAL = WEBConnection.getInstance();
      ReportEcxelController controller =new ReportEcxelController();
    private StreamedContent fileExporter;
       private String cpid = "";
    private String hdh = "";
    private String gameID = "";
    private String congTT = "";
    private String telco = "";
    private String loaiThongKe = "";
    private Date tuNgay = Calendar.getInstance().getTime();
    private Date denNgay = new java.sql.Date(0);
    private long giaTriTheNap = 0;
    private String page = "";
    private String loaiBD = "";
    
    private long tong1=0;
    private long tong2=0;
    private long tong3=0;
    private long tong4=0;
    
    public String getPage() {
        return page;
    }

    public void setPage(String page) {
        this.page = page;
    }

    /**
     * @return the cpid
     */
    public String getCpid() {
        return cpid;
    }

    /**
     * @param cpid the cpid to set
     */
    public void setCpid(String cpid) {
        this.cpid = cpid;
    }

    /**
     * @return the hdh
     */
    public String getHdh() {
        return hdh;
    }

    /**
     * @param hdh the hdh to set
     */
    public void setHdh(String hdh) {
        this.hdh = hdh;
    }

    /**
     * @return the gameID
     */
    public String getGameID() {
        return gameID;
    }

    /**
     * @param gameID the gameID to set
     */
    public void setGameID(String gameID) {
        this.gameID = gameID;
    }

    /**
     * @return the congTT
     */
    public String getCongTT() {
        return congTT;
    }

    /**
     * @param congTT the congTT to set
     */
    public void setCongTT(String congTT) {
        this.congTT = congTT;
    }

    /**
     * @return the telco
     */
    public String getTelco() {
        return telco;
    }

    /**
     * @param telco the telco to set
     */
    public void setTelco(String telco) {
        this.telco = telco;
    }

    /**
     * @return the loaiThongKe
     */
    public String getLoaiThongKe() {
        return loaiThongKe;
    }

    /**
     * @param loaiThongKe the loaiThongKe to set
     */
    public void setLoaiThongKe(String loaiThongKe) {
        this.loaiThongKe = loaiThongKe;
    }

    /**
     * @return the tuNgay
     */
    public Date getTuNgay() {
        return tuNgay;
    }

    /**
     * @param tuNgay the tuNgay to set
     */
    public void setTuNgay(Date tuNgay) {
        this.tuNgay = tuNgay;
    }

    /**
     * @return the denNgay
     */
    public Date getDenNgay() {
        return denNgay;
    }

    /**
     * @param denNgay the denNgay to set
     */
    public void setDenNgay(Date denNgay) {
        this.denNgay = denNgay;
    }

    /**
     * @return the giaTriTheNap
     */
    public long getGiaTriTheNap() {
        return giaTriTheNap;
    }

    /**
     * @param giaTriTheNap the giaTriTheNap to set
     */
    public void setGiaTriTheNap(long giaTriTheNap) {
        this.giaTriTheNap = giaTriTheNap;
    }

    /**
     * @return the loaiBD
     */
    public String getLoaiBD() {
        return loaiBD;
    }

    /**
     * @param loaiBD the loaiBD to set
     */
    public void setLoaiBD(String loaiBD) {
        this.loaiBD = loaiBD;
    }

    /**
     * @return the tong1
     */
    public long getTong1() {
        return tong1;
    }

    /**
     * @param tong1 the tong1 to set
     */
    public void setTong1(long tong1) {
        this.tong1 = tong1;
    }

    /**
     * @return the tong2
     */
    public long getTong2() {
        return tong2;
    }

    /**
     * @param tong2 the tong2 to set
     */
    public void setTong2(long tong2) {
        this.tong2 = tong2;
    }

    /**
     * @return the tong3
     */
    public long getTong3() {
        return tong3;
    }

    /**
     * @param tong3 the tong3 to set
     */
    public void setTong3(long tong3) {
        this.tong3 = tong3;
    }

    /**
     * @return the tong4
     */
    public long getTong4() {
        return tong4;
    }

    /**
     * @param tong4 the tong4 to set
     */
    public void setTong4(long tong4) {
        this.tong4 = tong4;
    }
    
    
    
    
    public List<RPT_TongCashoutModel> RPT_TongCashout() throws SQLException {
        List<RPT_TongCashoutModel> lst;
        WEBParamCollection Params = new WEBParamCollection();
        Params.add(this.getCpid());
        Params.add(this.getTelco());
        Params.add(this.getGiaTriTheNap());
        Params.add(this.getTuNgay());
        Params.add(this.getDenNgay());
        lst = DAL.executeQuery("{call RPT_TongCashout(?,?,?,?,?)}", Command.sqlStoredProcedure, Params, RPT_TongCashoutModel.class);

        return lst;

    }

    public PieChartModel RPT_TongCashout_Chart() throws SQLException {
        PieChartModel c = new PieChartModel();
        List<RPT_TongCashoutModel> lst;

       

        WEBParamCollection Params = new WEBParamCollection();
        Params.add(("-1".equals(this.getCpid()) ? "" : this.getCpid()));
        Params.add(("-1".equals(this.getTelco()) ? "" : this.getTelco()));
        Params.add(("-1".equals(this.getLoaiThongKe()) ? "" : this.getLoaiThongKe()));
        Params.add((this.getGiaTriTheNap() == -1 ? 0 : this.getGiaTriTheNap()));
        Params.add(this.getTuNgay());
        Params.add(this.getDenNgay());
        lst = DAL.executeQuery("{call RPT_TongCashout_Chart(?,?,?,?,?,?)}", Command.sqlStoredProcedure, Params, RPT_TongCashoutModel.class);
        
        
        
       for (RPT_TongCashoutModel m : lst) {
              c.set(m.getCpName() + " " + Utilities.formatNumber("#,###", m.getSoTien()), m.getSoTien());
              
            }
        
        return c;
    }

    public TreeNode RPT_TongCashout_ThongKe_Tong() throws SQLException {
        TreeNode root = new DefaultTreeNode(new RPT_TongCashoutModel(), null);
        WEBParamCollection Params = new WEBParamCollection();
        Params.add(("-1".equals(this.getCpid()) ? "" : this.getCpid()));
        Params.add(("-1".equals(this.getTelco()) ? "" : this.getTelco()));
        Params.add((this.getGiaTriTheNap() == -1 ? 0 : this.getGiaTriTheNap()));
        Params.add(this.getTuNgay());
        Params.add(this.getDenNgay());
        List<RPT_TongCashoutModel> lst = DAL.executeQuery("{call RPT_TongCashout_Chart_line_ngay(?,?,?,?,?)}", Command.sqlStoredProcedure, Params, RPT_TongCashoutModel.class);
        int i = 0;
        String strCPID;
        long lTong1=0;
        
        while (i < lst.size()) {
            RPT_TongCashoutModel m = new RPT_TongCashoutModel();
            m.setCpName(lst.get(i).getCpName());
            TreeNode noteParent = new DefaultTreeNode(m, root);
            noteParent.setExpanded(true);


            strCPID = lst.get(i).getCpid();

            long iCount = 0;
            if (i < lst.size()) {
                while (i < lst.size() && (lst.get(i).getCpid() == null ? strCPID == null : lst.get(i).getCpid().equals(strCPID))) {
                    lst.get(i).setCpName("");
                    noteParent.getChildren().add(new DefaultTreeNode(lst.get(i)));
                    iCount += lst.get(i).getSoTien();
                    lTong1+=lst.get(i).getSoTien();
                    i++;
                }
                m.setSoTien(iCount);
            }
            // i++;
        }
         this.setTong1(lTong1);
        this.setTong2(0);
        this.setTong3(0);
        return root;
    }

    public TreeNode RPT_TongCashout_ThongKe_ChiTiet() throws SQLException {
        TreeNode root = new DefaultTreeNode(new RPT_TongCashoutModel(), null);
        WEBParamCollection Params = new WEBParamCollection();
        Params.add(("-1".equals(this.getCpid()) ? "" : this.getCpid()));
        Params.add(("-1".equals(this.getTelco()) ? "" : this.getTelco()));
        Params.add(("-1".equals(this.getLoaiThongKe()) ? "" : this.getLoaiThongKe()));
        Params.add((this.getGiaTriTheNap() == -1 ? 0 : this.getGiaTriTheNap()));
        Params.add(this.getTuNgay());
        Params.add(this.getDenNgay());
        List<RPT_TongCashoutModel> lst = DAL.executeQuery("{call RPT_TongCashout(?,?,?,?,?,?)}", Command.sqlStoredProcedure, Params, RPT_TongCashoutModel.class);
        int i = 0;
        String strCPID;
        long lTong1=0;
        while (i < lst.size()) {
            RPT_TongCashoutModel m = new RPT_TongCashoutModel();
            m.setCpName(lst.get(i).getCpName());
            TreeNode noteParent = new DefaultTreeNode(m, root);
            noteParent.setExpanded(true);


            strCPID = lst.get(i).getCpid();

            long iCount = 0;
            if (i < lst.size()) {
                while (i < lst.size() && (lst.get(i).getCpid() == null ? strCPID == null : lst.get(i).getCpid().equals(strCPID))) {
                     String strTeleco = lst.get(i).getTelco();
                        RPT_TongCashoutModel m_Teleco = new RPT_TongCashoutModel();
                        m_Teleco.setCpName(lst.get(i).getTelco());
                        m_Teleco.setTelco("");

                        TreeNode noteParent_Teleco = new DefaultTreeNode(m_Teleco, noteParent);
                        noteParent_Teleco.setExpanded(true);
                        long lTongTel=0;
                        while (i < lst.size() && (lst.get(i).getTelco() == null ? strTeleco == null : lst.get(i).getTelco().equals(strTeleco))
                                && (lst.get(i).getCpid() == null ? strCPID == null : lst.get(i).getCpid().equals(strCPID))
                                ) {
                            //String strTeleco=lst.get(i).getTelco();
                            if(lst.get(i).getUserName().length()>=4)
                            {
                                lst.get(i).setUserName(lst.get(i).getUserName().substring(0, 4)+"****");
                            }
                            lst.get(i).setCpName(lst.get(i).getUserName());
                            lst.get(i).setTelco("");
//                            
                            RPT_TongCashoutModel m1 = lst.get(i);
                            noteParent_Teleco.getChildren().add(new DefaultTreeNode(m1));
                            

                            
                            iCount +=lst.get(i).getSoTien();
                            lTongTel+=lst.get(i).getSoTien();
                            lTong1+=lst.get(i).getSoTien();
                            m1.setSoTien(lst.get(i).getSoTien());
                           i++;
                                
                          
                           
                        }
                         m_Teleco.setSoTien(lTongTel);
                       // m_Teleco.setSoTien(0);
                        //m_Teleco.setTongTien((int) lMenhGia_Teleco);

                        //noteParent_CongTT.getChildren().add(noteParent_Teleco);
//                    lst.get(i).setCpName("");
//                    noteParent.getChildren().add(new DefaultTreeNode(lst.get(i)));
//                    iCount += lst.get(i).getSoTien();
//                    lTong1+=lst.get(i).getSoTien();
//                    i++;
                }
                m.setSoTien(iCount);
            }
            // i++;
        }
 this.setTong1(lTong1);
        this.setTong2(0);
        this.setTong3(0);
        return root;
    }
    
    
     public CartesianChartModel RPT_TongCashout_Chart_line_ngay() throws SQLException {
        CartesianChartModel c = new CartesianChartModel();
        List<RPT_TongCashoutModel> lst;

   

        WEBParamCollection Params = new WEBParamCollection();
         Params.add(("-1".equals(this.getCpid()) ? "" : this.getCpid()));
        Params.add(("-1".equals(this.getTelco()) ? "" : this.getTelco()));
        Params.add(("-1".equals(this.getLoaiThongKe()) ? "" : this.getLoaiThongKe()));
        Params.add((this.getGiaTriTheNap() == -1 ? 0 : this.getGiaTriTheNap()));
        Params.add(this.getTuNgay());
        Params.add(this.getDenNgay());
       lst = DAL.executeQuery("{call RPT_TongCashout_Chart_line_ngay(?,?,?,?,?,?)}", Command.sqlStoredProcedure, Params, RPT_TongCashoutModel.class);
        
        if(Sys_NguoiDungController.findUser().isIsAdmin())
        {
            List<RPT_TongCashoutModel> lst1=DAL.executeQuery("Select distinct CPID,CPName from users_report where users_report.CPID<>''",RPT_TongCashoutModel.class);
            for(RPT_TongCashoutModel m:lst1)
            {
                LineChartSeries l=new LineChartSeries();
                l.setLabel("Tồng tiền theo " + m.getCpName());
                int i=0;
                boolean bln=false;
                while(i<lst.size())
                {
                    if(!l.getData().containsKey(Utilities.parseDateTime(lst.get(i).getNgay(), "dd/MM")))
                    {
                        l.set(Utilities.parseDateTime(lst.get(i).getNgay(), "dd/MM"), 0);
                        l.setShowLine(true);
                    }
                    if(lst.get(i).getCpid() == null ? m.getCpid() == null : lst.get(i).getCpid().equals(m.getCpid()))
                    {
                         l.set(Utilities.parseDateTime(lst.get(i).getNgay(), "dd/MM"), lst.get(i).getSoTien());
                         l.setShowLine(true);
                         bln=true;
                    }
                    i++;
                }
                if(bln)
                    c.addSeries(l);
            }
            
            LineChartSeries l1=new LineChartSeries();
            l1.setLabel("Tổng số tiền");
            int i=0;
            while(i<lst.size())
            {

                  l1.set(Utilities.parseDateTime(lst.get(i).getNgay(), "dd/MM"), lst.get(i).getTongTien());
                 l1.setShowLine(true);
                     i++;
             
                  
            }
            
            
             c.addSeries(l1);
             
        }
        else
        {
           
            LineChartSeries l2=new LineChartSeries();
            l2.setLabel("Tổng số tiền nạp theo CP");

            for (RPT_TongCashoutModel m : lst) {
               
                l2.set(Utilities.parseDateTime(m.getNgay(), "dd/MM"),m.getSoTien());
                l2.setShowLine(true);    

            }
             
             c.addSeries(l2);
        }
        
        return c;
    }
     public CartesianChartModel RPT_TongCashout_Chart_line_thang() throws SQLException {
        CartesianChartModel c = new CartesianChartModel();
        List<RPT_TongCashoutModel> lst;

   

        WEBParamCollection Params = new WEBParamCollection();
        Params.add(("-1".equals(this.getCpid()) ? "" : this.getCpid()));
        Params.add(("-1".equals(this.getTelco()) ? "" : this.getTelco()));
        Params.add(("-1".equals(this.getLoaiThongKe()) ? "" : this.getLoaiThongKe()));
        Params.add((this.getGiaTriTheNap() == -1 ? 0 : this.getGiaTriTheNap()));
        Params.add(this.getTuNgay());
        Params.add(this.getDenNgay());
       lst = DAL.executeQuery("{call RPT_TongCashout_Chart_line_thang(?,?,?,?,?,?)}", Command.sqlStoredProcedure, Params, RPT_TongCashoutModel.class);
        
        if(Sys_NguoiDungController.findUser().isIsAdmin())
        {
            List<RPT_TongCashoutModel> lst1=DAL.executeQuery("Select distinct CPID,CPName from users_report where users_report.CPID<>''",RPT_TongCashoutModel.class);
            for(RPT_TongCashoutModel m:lst1)
            {
                LineChartSeries l=new LineChartSeries();
                l.setLabel("Tồng tiền theo " + m.getCpName());
                int i=0;
                boolean bln=false;
                while(i<lst.size())
                {
                    if(!l.getData().containsKey(lst.get(i).getThang()))
                    {
                        l.set(lst.get(i).getThang(), 0);
                        l.setShowLine(true);
                    }
                    if(lst.get(i).getCpid() == null ? m.getCpid() == null : lst.get(i).getCpid().equals(m.getCpid()))
                    {
                         l.set(lst.get(i).getThang(), lst.get(i).getSoTien());
                         l.setShowLine(true);
                         bln=true;
                    }
                    i++;
                }
                if(bln)
                    c.addSeries(l);
            }
            
            LineChartSeries l1=new LineChartSeries();
            l1.setLabel("Tổng số tiền");
            int i=0;
            while(i<lst.size())
            {

                  l1.set(lst.get(i).getThang(), lst.get(i).getTongTien());
                 l1.setShowLine(true);
                     i++;
             
                  
            }
            
            
             c.addSeries(l1);
             
        }
        else
        {
           
            LineChartSeries l2=new LineChartSeries();
            l2.setLabel("Tổng số tiền nạp theo CP");

            for (RPT_TongCashoutModel m : lst) {
               
                l2.set(m.getNgay(),m.getSoTien());
                l2.setShowLine(true);    

            }
             
             c.addSeries(l2);
        }
        
        return c;
    }

    public void cmd_RPT_TongCashout_Excel_Click(ActionEvent event) throws SQLException, ParseException {
        Map mapParams = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
        this.setCpid(String.valueOf(mapParams.get("CPID")));
        this.setGameID(String.valueOf(mapParams.get("Game")));
        this.setTelco(String.valueOf(mapParams.get("Teleco")));
        this.setLoaiThongKe(String.valueOf(mapParams.get("BaoCao")));
        this.setGiaTriTheNap(Long.parseLong(mapParams.get("MenhGia").toString()));
        String strTuNgay = String.valueOf(mapParams.get("TuNgay"));
        String strDenNgay = String.valueOf(mapParams.get("DenNgay"));
        setTuNgay(Utilities.parseDate(strTuNgay, "dd/MM/yyyy"));
        setDenNgay(Utilities.parseDate(strDenNgay, "dd/MM/yyyy"));
        
        WEBParamCollection Params = new WEBParamCollection();
       
        Params.add(("-1".equals(this.getCpid()) ? "" : this.getCpid()));
        Params.add(("-1".equals(this.getTelco()) ? "" : this.getTelco()));
        Params.add(("-1".equals(this.getLoaiThongKe()) ? "" : this.getLoaiThongKe()));
        Params.add((this.getGiaTriTheNap() == -1 ? 0 : this.getGiaTriTheNap()));
        Params.add(this.getTuNgay());
        Params.add(this.getDenNgay());
        
        List<RPT_TongCashoutModel> lst = DAL.executeQuery("{call RPT_TongCashout(?,?,?,?,?,?)}", Command.sqlStoredProcedure, Params, RPT_TongCashoutModel.class);
         setFileExporter(controller.tongTienCashOutChiTietToExcel(tuNgay, denNgay, lst));
//        if (!"1".equals(String.valueOf(mapParams.get("BaoCao")))) {
//           
//        } else {
//            lst = DAL.executeQuery("{call RPT_TongCashout_Tong(?,?,?,?,?)}", Command.sqlStoredProcedure, Params, RPT_TongCashoutModel.class);
//            setFileExporter(controller.tongTienCashOutTongToExcel(tuNgay, denNgay, lst));
//        }

        if (getFileExporter() != null) {
            try {
                Utilities.deleteFile(new File(controller.getLocalPath() + "/" + getFileExporter().getName()));
            } catch (IOException ex) {
                Logger.getLogger(ReportController.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    public void cmd_RPT_TongCashout_ThongKe_Click(ActionEvent event) throws SQLException, ParseException {
        Map mapParams = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
      this.setCpid(String.valueOf(mapParams.get("CPID")));
        this.setGameID(String.valueOf(mapParams.get("Game")));
        this.setTelco(String.valueOf(mapParams.get("Teleco")));
        this.setLoaiThongKe(String.valueOf(mapParams.get("BaoCao")));
        this.setGiaTriTheNap(Long.parseLong(mapParams.get("MenhGia").toString()));
        String strTuNgay = String.valueOf(mapParams.get("TuNgay"));
        String strDenNgay = String.valueOf(mapParams.get("DenNgay"));
        setTuNgay(Utilities.parseDate(strTuNgay, "dd/MM/yyyy"));
        setDenNgay(Utilities.parseDate(strDenNgay, "dd/MM/yyyy"));
        this.setPage("/layout/Web/tongcashout_chitiet.xhtml");


    }

    public void cmd_RPT_TongCashout_Chart_Click(ActionEvent event) throws SQLException, ParseException {
        Map mapParams = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
        this.setCpid(String.valueOf(mapParams.get("CPID")));
        this.setGameID(String.valueOf(mapParams.get("Teleco")));
        this.setLoaiThongKe(String.valueOf(mapParams.get("BaoCao")));
        this.setGiaTriTheNap(Long.parseLong(mapParams.get("MenhGia").toString()));
        String strTuNgay = String.valueOf(mapParams.get("TuNgay"));
        String strDenNgay = String.valueOf(mapParams.get("DenNgay"));
        setTuNgay(Utilities.parseDate(strTuNgay, "dd/MM/yyyy"));
        setDenNgay(Utilities.parseDate(strDenNgay, "dd/MM/yyyy"));
        
        this.setLoaiBD(String.valueOf(mapParams.get("Loai")));

         switch (this.getLoaiBD()) {
            case "2":
                this.setPage("/layout/Chart/tongcashout.xhtml");
                break;
            case "4":
                this.setPage("/layout/Chart/tongcashout_line_ngay.xhtml");
                break;
            case "5":
                this.setPage("/layout/Chart/tongcashout_line_thang.xhtml");
                break;
        }
        
    }

    /**
     * @return the fileExporter
     */
    public StreamedContent getFileExporter() {
        return fileExporter;
    }

    /**
     * @param fileExporter the fileExporter to set
     */
    public void setFileExporter(StreamedContent fileExporter) {
        this.fileExporter = fileExporter;
    }

}
